package com.douqu.game.core.entity.ext.data.boon;

import com.bean.core.buffer.ByteBuffer;
import com.douqu.game.core.config.AltarConfig;
import com.douqu.game.core.config.PurchaseTimesConfig;
import com.douqu.game.core.config.VipConfig;
import com.douqu.game.core.config.drop.DropGroupConfig;
import com.douqu.game.core.controller.PlayerController;
import com.douqu.game.core.entity.Player;
import com.douqu.game.core.entity.db.TaskDB;
import com.douqu.game.core.entity.ext.BagInfo;
import com.douqu.game.core.entity.ext.TaskInfo;
import com.douqu.game.core.entity.ext.data.BaseData;
import com.douqu.game.core.factory.*;
import com.douqu.game.core.protobuf.SGCommonProto;
import com.douqu.game.core.protobuf.SGMainProto;
import com.douqu.game.core.protobuf.SGPlayerProto;
import com.douqu.game.core.util.CoreUtils;
import com.douqu.game.core.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: Bean
 * @Description:
 * @Date: 2017-10-30 17:06
 */
public class AltarData extends BaseData {

    /**
     * 玩家祭坛数据
     */
    public Map<Integer, SingleBoonData> altarMap;

    private Player player;

    public AltarData(Player player) {
        this.player = player;
        altarMap = new ConcurrentHashMap<>();
    }


    @Override
    public void init() {
        List<AltarConfig> list = DataFactory.getInstance().getDataList(DataFactory.ALTAR_KEY);
        for (AltarConfig altarConfig : list) {
            altarMap.put(altarConfig.id, new SingleBoonData(player, DataFactory.ALTAR_KEY, altarConfig.id));
        }
    }

    @Override
    public void checkInit() {
        if (altarMap.size() == 0) {
            init();
        } else {
            //验证祭坛数是否够  这个方法可以新增新的祭坛
            List<AltarConfig> configList = DataFactory.getInstance().getDataList(DataFactory.ALTAR_KEY);
            if (altarMap.size() != configList.size()) {
                for (AltarConfig altarConfig : configList) {
                    if (altarMap.get(altarConfig.id) == null) {
                        altarMap.put(altarConfig.id, new SingleBoonData(player, DataFactory.ALTAR_KEY, altarConfig.id));
                    }
                }
            }
        }
    }

    @Override
    public void reset() {
        for (Map.Entry<Integer, SingleBoonData> entry : altarMap.entrySet()) {
            entry.getValue().clear();
        }
    }

    @Override
    public void checkReset() {
        for (Map.Entry<Integer, SingleBoonData> entry : altarMap.entrySet()) {
            if (!entry.getValue().isTodayByOffset()) {
                reset();
                break;
            }
        }

    }

    @Override
    public void writeTo(ByteBuffer buffer)
    {
        buffer.writeByte(altarMap.size());
        for(Map.Entry<Integer, SingleBoonData> entry : altarMap.entrySet())
        {
            entry.getValue().writeTo(buffer);
            buffer.writeByte(entry.getKey());
        }
    }

    @Override
    public void loadFrom(ByteBuffer buffer) {
        int size = buffer.readByte();
        SingleBoonData altar = null;
        for (int i = 0; i < size; i++) {
            altar = new SingleBoonData(player, DataFactory.ALTAR_KEY);
            altar.loadFrom(buffer);
            altarMap.put(buffer.readByte(), altar);
        }
    }

    /**
     * 检测红点
     *
     * @return
     */
    public boolean hasRedPointRemind()
    {
        if(!CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_ALTAR_SYSTEM, player)){
            return false;
        }
        for(Map.Entry<Integer, SingleBoonData> entry : altarMap.entrySet())
        {
            if(CoreUtils.checkAltarFunctionOpen(entry.getKey(), player) == null){
                if(entry.getValue().freeCount > 0){
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 祭祀
     */
    public void getAltarReward(PlayerController playerController, int id) {
        if (id <= 0) {
            playerController.sendWarn(WordFactory.PARAM_ERROR);
            return;
        } else {
            //检测功能开启
            String funOpenStr = CoreUtils.checkAltarFunctionOpen(id, playerController.getPlayer());
            if (!StringUtils.isNullOrEmpty(funOpenStr)) {
                playerController.sendWarn(funOpenStr);
                return;
            }
        }

        SingleBoonData altarData = altarMap.get(id);
        if (altarData == null) {
            playerController.sendWarn(WordFactory.CURRENT_ALTAR);
            return;
        }
        BagInfo bagInfo = playerController.getPlayer().getExtInfo(BagInfo.class);
        //根据id 获取配置文件数据
        AltarConfig altarConfig = DataFactory.getInstance().getGameObject(DataFactory.ALTAR_KEY, altarData.id);
        //获取购买次数 当前的总次数 - 配置的免费次数
        int hasBuyTimes = altarData.getBuyTimes();
        int assetsCount = 0;
        //查询当前下次的购买价格
        if (hasBuyTimes >= 0) {
            PurchaseTimesConfig timesConfig = DataFactory.getInstance().getGameObject(DataFactory.PURCHASE_KEY, hasBuyTimes + 1);
            assetsCount = timesConfig.altarBuyPriceMap.get(altarData.id);
//            CommonData commonData = altarConfig.getDropCommonData(altarData.currentNum);
            if (bagInfo.getAsset(ConfigFactory.ASSET_MONEY_KEY) < assetsCount) {
                //资源不够
                playerController.sendWarn(WordFactory.ASSET_NOT_ENOUGH, ConfigFactory.ASSET_MONEY_KEY);
                return;
            }
        }

        //获取奖励id
        int dropId = altarConfig.getAltarDrop(playerController);
        DropGroupConfig dropGroupConfig = DataFactory.getInstance().getGameObject(DataFactory.DROP_GROUP_KEY, dropId);
        if (dropGroupConfig == null) {
            //掉落资源为空
            playerController.sendWarn(WordFactory.CURRENT_ALTAR);
            return;
        }

        long currentTime = DataFactory.currentTime;
        VipConfig vipConfig = DataFactory.getInstance().getGameObject(DataFactory.VIP_KEY, player.getVipLevel());
        //每日抽奖次数大于最大次数
        if (altarData.currentNum >= vipConfig.altarFreeTimesMap.get(altarData.id) + vipConfig.altarPurchaseMaxMap.get(altarData.id)) {
            //不能参与祭祀 每日次数上限
            playerController.sendWarn(WordFactory.CURRENT_NUM_LIMITATION, altarData.currentNum);
            return;
        } else {
            altarData.currentNum++;
            altarData.lastUpdateTime = currentTime;
        }
        int everydayResidueCount = altarData.getRemainTimes();
        //免费次数大于0 减去免费次数
        if (altarData.freeCount > 0) {
            altarData.freeCount--;
        } else {
            if (assetsCount > 0)
                bagInfo.addAsset(ConfigFactory.ASSET_MONEY_KEY, -assetsCount);
        }
        // 检测任务是否完成
        if (id == AltarFactory.EXP) {
            playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_EVERYDAY_EXP_JITAN, 1);
        } else if (id == AltarFactory.GOLD) {
            playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_EVERYDAY_GOLD_JITAN, 1);
        } else if (id == AltarFactory.ORNAMENT_STRENGTH) {
            playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_EVERYDAY_SHIPIN_QIANGHUA, 1);
        } else if (id == AltarFactory.EQUIP) {
            playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_EVERYDAY_EQUIP_JITAN, 1);
        } else if (id == AltarFactory.ORNAMENT_REFINE) {
            playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_EVERYDAY_SHIPIN_JINTAN, 1);
        } else if (id == AltarFactory.MEDICINE) {
            playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_EVERYDAY_YAOSHUI_JITAN, 1);
        }
        // 检测任务是否完成
        playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_EVERY_ALTAR, 1);
        //记录第一次时间
        if (altarData.getFirstLotteryTime() == 0){
            altarData.setFirstLotteryTime(DataFactory.currentTime);
        }
        //掉落
        SGPlayerProto.S2C_Sacrifice.Builder b = SGPlayerProto.S2C_Sacrifice.newBuilder();
        dropGroupConfig.dropRewardResult(bagInfo);
        b.setId(id);
        b.setFreeCount(altarData.freeCount);
        b.setEverydayResidueCount(everydayResidueCount);

        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Altar_Sacrifice_VALUE, b.build().toByteArray());
    }

    public void altarInit(PlayerController playerController) {
        SGPlayerProto.S2C_AltarInit.Builder b = SGPlayerProto.S2C_AltarInit.newBuilder();
        List<AltarConfig> list = DataFactory.getInstance().getDataList(DataFactory.ALTAR_KEY);
        SGPlayerProto.AltarInit.Builder c = SGPlayerProto.AltarInit.newBuilder();
        SingleBoonData altarData = null;
        for (AltarConfig altarConfig : list) {
            altarData = altarMap.get(altarConfig.id);
            c.setId(altarConfig.id);
//            c.setEverydayResidueCount(altarConfig.everydayMaxCount - altarData.currentNum);
            c.setEverydayResidueCount(altarData.getRemainTimes());
            c.setFreeCount(altarData.freeCount);
            b.addAltarInit(c);
        }
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Altar_Init_VALUE, b.build().toByteArray());
    }
}
